package com.dingding.transfer.stamper.config;

import com.dingding.transfer.stamper.constant.RabbitConstants;
import com.dingding.transfer.stamper.handler.RabbitMsgCallback;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/4/8 13:37
 **/
@Configuration
public class RabbitConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, RabbitMsgCallback rabbitMsgCallback) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setConfirmCallback(rabbitMsgCallback);
        rabbitTemplate.setReturnCallback(rabbitMsgCallback);
        return rabbitTemplate;
    }

    @Bean(name = "delayQueue")
    public Queue delayQueue(){
        return new Queue(RabbitConstants.Queue.DELAY_QUEUE_NAME);
    }

    @Bean
    public CustomExchange delayExchange(){
        Map<String,Object> args = new HashMap<>();
        args.put("x-delayed-type","direct");
        return new CustomExchange(RabbitConstants.Exchange.DELAY_EXCHANGE_NAME,"x-delayed-message",true,false,args);
    }

    @Bean
    public Binding bindQueue2Exchange(Queue delayQueue, CustomExchange customExchange){
        return BindingBuilder.bind(delayQueue).to(customExchange).with(RabbitConstants.RoutingKey.DELAY_ROUTING_KEY).noargs();
    }
}
